#!/bin/sh

COMMAND=$1
SYSSTAT=$2

TOOLNAME=yapcg
TOOLDIR=/tmp/$TOOLNAME
PIDDIR=/tmp/$TOOLNAME

startProcess() {
   PIDFILE="$1"
   OUTFILE="$2"
   shift 2
   COMMAND="$*"
   echo "About to start process: $COMMAND"
   nohup $COMMAND > $OUTFILE &
   echo $! > $PIDDIR/$PIDFILE
}

stopProcess() {
   PIDFILE=$PIDDIR/$1
   PID=`cat $PIDFILE`
   echo "About to kill process $PID..."
   kill $PID
   wait $PID
   echo "Process $PID terminated, removing pidfile"
   rm $PIDFILE
   echo "Pidfile: $PIDFILE removed..."
}


if [ ! -d $PIDDIR ]; then
   echo "Creating tmp ($PIDDIR) directory..."
   mkdir $PIDDIR;
fi

case $COMMAND in
   start) 
	  SAMPLING_PERIOD=1
	  START_DATE=`date +%Y%m%d_%H%M%S`
	  export LC_TIME=POSIX
	  startProcess "sarmem.pid" "sarmem$START_DATE.out" "sar -r $SAMPLING_PERIOD"
	  startProcess "sarcpu.pid" "sarcpu$START_DATE.out" "sar $SAMPLING_PERIOD"
          if [ "`pidstat -V | head -1 | cut -f3 -d' ' | cut -f1 -d'.'`"=="10" ]; then
	     echo "Pidstat version 10 detected, adding stack statistics option..."
	     PIDSTAT_OPTIONS="-dursh"
          else
	     echo "Pidstat older version (<10) detected, output will be generated without stack statistics option..."
	     PIDSTAT_OPTIONS="-durh"
          fi
          startProcess "pidstat.pid" "pidstat$START_DATE.out" "pidstat $PIDSTAT_OPTIONS 2"
	  ;;
   stop)
	  stopProcess "sarmem.pid"
	  stopProcess "sarcpu.pid"
	  stopProcess "pidstat.pid"

	  ;;
   clean)
	  echo "Removing tmp ($PIDDIR) directory..."
	  rm -Rf $PIDDIR
	  ;;
   *)
	  echo "Syntax: $0 [start|stop|clean]"
          ;;
esac
